package com.cloudcc.frame.comclass;

import com.cloudcc.deveditor.core.CCObject;
import com.cloudcc.deveditor.core.ServiceResult;
import com.cloudcc.deveditor.core.UserInfo;
import com.cloudcc.frame.Utils.CompanyBaseInfoService;
import com.cloudcc.frame.Utils.CompanyInfoCountService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class SaveAccount {


    private static MyCCservice cs;

    private UserInfo userInfo;

    /*管户小组的管户状态*/
    private String lnForce = "已生效";
    private String expired = "已失效";

    /*客户的跟进状态*/
    private String accountFollowStatus = "待分配";
    private String accountType = "20211C59581DC5CZOn5N";

    public SaveAccount(UserInfo userInfo) throws Exception {
        cs = new MyCCservice(userInfo);
        this.userInfo = userInfo;
    }

    public SaveAccount() throws Exception {
        cs = new MyCCservice(userInfo);
        this.userInfo = userInfo;
    }


    /*线下保函的url*/
    private String url = "/pfbpapi/crm/coupon/cust/manage/querystatus";
    private String port = "http://118.244.210.132:80";
    /*获取登录token*/
    private String getToken = "http://118.244.210.132:80/oauth2/oauth/token";
    private String LOGINGCODE = "200";
    private String RESUITCODE = "0000";
    private String ERRORCODE = "1200277";


    /*客户保存*/
    public String saveAccount(String data) throws Exception {


        JSONObject jsonDate = new JSONObject();
        String userId = userInfo.getUserId();
        JSONObject dataInfo = JSONObject.fromObject(data);
        JSONObject accountInfos = JSONObject.fromObject(dataInfo.get("Account"));
        JSONObject eleOpenInfo = JSONObject.fromObject(dataInfo.get("ele_open_info"));
        JSONObject eleNumum = JSONObject.fromObject(dataInfo.get("ele_num"));
        String ggzyjyzx = eleNumum.getString("ggzyjyzx");
        accountInfos.put("ggzyjyzx", ggzyjyzx);
        String accountIds = saveAccountInfo(accountInfos);
        JSONObject jsonObject1 = JSONObject.fromObject(accountIds);
        if (!jsonObject1.getString("code").equals("200")) {
            return String.valueOf(jsonObject1);
        } else {
            String accountId = jsonObject1.getString("id");
            eleOpenInfo.put("fk_account", accountId);
            eleNumum.put("fk_account", accountId);
            JSONObject manageGroup = JSONObject.fromObject(dataInfo.get("manage_grounp"));
            String code = accountInfos.get("tyshxydm") + "";
            String fk_psmc = eleNumum.get("ggzyjyzx") == null ? "" : eleNumum.get("ggzyjyzx") + "";
            String ghqy = manageGroup.get("ghqy") + "";
            /*省份，城市，区县 3字段带确认*/
            String province = manageGroup.get("jysf") + "";
            String gfkCityNamehqy = manageGroup.get("jysq") + "";
            String fkCountryName = manageGroup.get("jyqx") + "";
            String lxdz = manageGroup.get("lxdz") + "";
            String findGhsql = "select id,fk_ccuser from manage_group where fk_psmc ='" + ghqy + "' and ghzt!='" + expired + "' " +
                    "and name ='" + code + "' " +
                    "and is_deleted='0' ";
            List<CCObject> manageGroupInfo = cs.cqlQuery("manage_group", findGhsql);
            if (manageGroupInfo.size() > 0) {
                String groupInfo = manageGroupInfo.get(0).get("fk_ccuser") == null ? "" : manageGroupInfo.get(0).get("fk_ccuser") + "";
                String is_shared = "是";
                String jyzxInfo = "select jyzx from ghjl where yh ='" + groupInfo + "' ";
                String userjyzxInfo = "select jyzx from ghjl where yh ='" + userId + "' ";
                List<CCObject> ghjl = cs.cqlQuery("ghjl", jyzxInfo);
                List<CCObject> ghjl1 = cs.cqlQuery("ghjl", userjyzxInfo);
                if (ghjl.get(0).get("jyzx").equals(ghjl1.get(0).get("jyzx"))) {
                    jsonDate.put("msg", "当前已存在项目经理，并且为统一公共资源交易中心的");
                    jsonDate.put("code", "301");
                    return String.valueOf(jsonDate);
                } else {
                    JSONObject info = new JSONObject();
                    info.put("accountId", accountId);
                    info.put("userId", userId);
                    info.put("is_shared", is_shared);
                    info.put("code", code);
                    info.put("province", province);
                    info.put("gfkCityNamehqy", gfkCityNamehqy);
                    info.put("fkCountryName", fkCountryName);
                    info.put("fk_psmc", fk_psmc);
                    info.put("lxdz", lxdz);
                    String gen = gen(lxdz);
                    String wd = "";
                    String jd = "";
                    JSONObject genInfo = JSONObject.fromObject(gen);
                    try {
                        JSONObject jsonObject = JSONObject.fromObject(genInfo);
                        JSONArray geocodes = jsonObject.getJSONArray("geocodes");
                        String location = geocodes.getJSONObject(0).getString("location");
                        String[] split = location.split(",");
                        wd = split[0];
                        jd = split[1];
                    } catch (Exception e) {
                    }
                    info.put("dlwzco", jd);
                    info.put("dlwzla", wd);
                    sharedClient(info);
                    saveEleOpenInfo(eleOpenInfo);
                    savaEleNum(eleNumum);
                    jsonDate.put("id", accountId);
                    jsonDate.put("data", "保存成功");
                    jsonDate.put("code", "200");
                    return String.valueOf(jsonDate);
                }
            } else {
                String is_shared = "否";
                JSONObject info = new JSONObject();
                info.put("accountId", accountId);
                info.put("userId", userId);
                info.put("is_shared", is_shared);
                info.put("code", code);
                info.put("province", province);
                info.put("gfkCityNamehqy", gfkCityNamehqy);
                info.put("fkCountryName", fkCountryName);
                info.put("fk_psmc", fk_psmc);
                info.put("lxdz", lxdz);
                String gen = gen(lxdz);
                String wd = "";
                String jd = "";
                JSONObject genInfo = JSONObject.fromObject(gen);
                try {
                    JSONObject jsonObject = JSONObject.fromObject(genInfo);
                    JSONArray geocodes = jsonObject.getJSONArray("geocodes");
                    String location = geocodes.getJSONObject(0).getString("location");
                    String[] split = location.split(",");
                    wd = split[0];
                    jd = split[1];
                } catch (Exception e) {
                }
                info.put("dlwzco", jd);
                info.put("dlwzla", wd);
                sharedClient(info);
                saveEleOpenInfo(eleOpenInfo);
                savaEleNum(eleNumum);
                jsonDate.put("code", "200");
                jsonDate.put("id", accountId);
                jsonDate.put("data", "保存成功");
                return String.valueOf(jsonDate);
            }
        }
    }

    /*查询客户是否拾回*/
    public String findAccountRetrieve(String data) {
        String ACCOUNTTYPE = "待分配";
        JSONObject jsonObject = new JSONObject();
        String tyshxydm = JSONObject.fromObject(data).getString("tyshxydm");
        String ggzyjyzx = JSONObject.fromObject(data).getString("ggzyjyzx");
        String syr = JSONObject.fromObject(data).getString("syr");
        String findAccountSql = "select id,follow_status from Account where invoiceTaxNo ='" + tyshxydm + "' and is_deleted='0' ";
        List<CCObject> ccObjects = cs.cqlQuery("Account", findAccountSql);
        if (ccObjects.size() > 0) {
            String accountId = ccObjects.get(0).get("id") == null ? "" : ccObjects.get(0).get("id") + "";
            String follow_status = ccObjects.get(0).get("follow_status") == null ? "" : ccObjects.get(0).get("follow_status") + "";
            String findSql = "select id from manage_group where fk_psmc ='" + ggzyjyzx + "' and fk_ccuser='" + syr + "' and fk_account='" + accountId + "' and is_deleted='0' and ghzt='已失效' ";
            List<CCObject> retrieveApply = cs.cqlQuery("manage_group", findSql);
            if (retrieveApply.size() > 0) {
                jsonObject.put("code", "505");
                jsonObject.put("msg", "请前往拾回页面填写拾回申请");
                jsonObject.put("id", accountId);
                return String.valueOf(jsonObject);
            }
            if (follow_status.equals(ACCOUNTTYPE)) {
                jsonObject.put("code", "502");
                jsonObject.put("msg", "点击共享客户,获取您对客户的管户权");
                jsonObject.put("id", accountId);
                return String.valueOf(jsonObject);
            } else {
                jsonObject.put("code", "502");
                jsonObject.put("msg", "点击领取客户，领取您对客户的管户权");
                return String.valueOf(jsonObject);
            }

        }
        jsonObject.put("code", "200");
        jsonObject.put("data", "");
        return String.valueOf(jsonObject);
    }

    //    公招信息中的客户投标频率
    public String findEleNum() {
        String findEleNum = "select a.frequece frequece ,d.name  name ,a.fk_psmc fkPsmc,a.id from ele_num  a " +
                "inner join ghjl b  on a.fk_psmc  = b.jyzx  and b.is_deleted='0' " +
                "inner join ccuser c on c.id = b.yh  and c.id ='" + userInfo.getUserId() + "' and c.is_deleted='0' " +
                "inner join psmc d on  d.id = a.fk_psmc and d.is_deleted='0' ";
        List<CCObject> ccObjects = cs.cqlQuery("", findEleNum);
        JSONArray dataInfoList = new JSONArray();
        if (ccObjects.size() > 0) {
            for (CCObject cc : ccObjects) {
                JSONObject dataInfo = new JSONObject();
                String fkpsmc = cc.get("fkpsmc") == null ? "" : cc.get("fkpsmc") + "";
                String name = cc.get("name") == null ? "" : cc.get("name") + "";
                String frequece = cc.get("frequece") == null ? "" : cc.get("frequece") + "";
                String id = cc.get("id") == null ? "" : cc.get("id") + "";
                dataInfo.put("frequece", frequece);
                JSONObject jyzxInfo = new JSONObject();
                jyzxInfo.put("label", name);
                jyzxInfo.put("value", fkpsmc);
                dataInfo.put("id", id);
                dataInfo.put("fkpsmc", jyzxInfo);
                dataInfoList.add(dataInfo);
            }
        }
        return String.valueOf(dataInfoList);
    }

    /*共享客户创建管户权*/
    public String sharedAccount(String data) throws Exception {
        JSONObject jsonDate = new JSONObject();
        JSONObject jsonObjectInfo = JSONObject.fromObject(data);
        String lxdz = jsonObjectInfo.getString("lxdz");
        String is_shared = "是";
        JSONObject info = new JSONObject();
        info.put("accountId", jsonObjectInfo.getString("id"));
        info.put("userId", jsonObjectInfo.getString("syr"));
        info.put("is_shared", is_shared);
        info.put("code", jsonObjectInfo.getString("tyshxydm"));
        info.put("province", jsonObjectInfo.getString("zcsf"));
        info.put("gfkCityNamehqy", jsonObjectInfo.getString("zcsq"));
        info.put("fkCountryName", jsonObjectInfo.getString("zcqx"));
        info.put("fk_psmc", jsonObjectInfo.getString("ggzyjyzx"));
        info.put("lxdz", lxdz);
        String gen = gen(lxdz);
        String wd = "";
        String jd = "";
        JSONObject genInfo = JSONObject.fromObject(gen);
        try {
            JSONObject jsonObject = JSONObject.fromObject(genInfo);
            JSONArray geocodes = jsonObject.getJSONArray("geocodes");
            String location = geocodes.getJSONObject(0).getString("location");
            String[] split = location.split(",");
            wd = split[0];
            jd = split[1];
        } catch (Exception e) {
        }
        info.put("dlwzco", jd);
        info.put("dlwzla", wd);
        sharedClient(info);
        jsonDate.put("code", "200");
        jsonDate.put("data", "保存成功");
        jsonDate.put("id", jsonObjectInfo.getString("id"));
        return String.valueOf(jsonDate);
    }

    /*领取客户管户权*/
    public String receiveAccount(String data) throws Exception {
        JSONObject jsonDate = new JSONObject();
        JSONObject jsonObjectInfo = JSONObject.fromObject(data);
        String lxdz = jsonObjectInfo.getString("lxdz");
        String is_shared = "否";
        JSONObject info = new JSONObject();
        info.put("accountId", jsonObjectInfo.getString("id"));
        info.put("userId", jsonObjectInfo.getString("syr"));
        info.put("is_shared", is_shared);
        info.put("code", jsonObjectInfo.getString("tyshxydm"));
        info.put("province", jsonObjectInfo.getString("zcsf"));
        info.put("gfkCityNamehqy", jsonObjectInfo.getString("zcsq"));
        info.put("fkCountryName", jsonObjectInfo.getString("zcqx"));
        info.put("fk_psmc", jsonObjectInfo.getString("ggzyjyzx"));
        info.put("lxdz", lxdz);
        String gen = gen(lxdz);
        String wd = "";
        String jd = "";
        JSONObject genInfo = JSONObject.fromObject(gen);
        try {
            JSONObject jsonObject = JSONObject.fromObject(genInfo);
            JSONArray geocodes = jsonObject.getJSONArray("geocodes");
            String location = geocodes.getJSONObject(0).getString("location");
            String[] split = location.split(",");
            wd = split[0];
            jd = split[1];
        } catch (Exception e) {
        }
        info.put("dlwzco", jd);
        info.put("dlwzla", wd);
        sharedClient(info);
        jsonDate.put("code", "200");
        jsonDate.put("data", "保存成功");
        jsonDate.put("id", jsonObjectInfo.getString("id"));
        return String.valueOf(jsonDate);
    }


    /*获取客户企业性质的下拉列表*/
    public String picklistValue() throws Exception {

        List<Object> psmclist = new ArrayList<Object>();
        List<Map> AccountMap = cs.getPicklistValue("Account", "qyxz", "");
        if (AccountMap.size() > 0) {
            for (Map m : AccountMap) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", m.get("key"));
                jsonObject.put("label", m.get("key"));
                psmclist.add(jsonObject);
            }
        }
        return String.valueOf(psmclist);
    }

    /*电子保函公招信息的主要投标工程类别的下拉列表*/
    public String pickEleOpenInfoValue() throws Exception {
        List<Object> psmclist = new ArrayList<Object>();
        List<Map> AccountMap = cs.getPicklistValue("ele_open_info", "main_type", "");
        if (AccountMap.size() > 0) {
            for (Map m : AccountMap) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", m.get("key"));
                jsonObject.put("label", m.get("key"));
                psmclist.add(jsonObject);
            }
        }
        return String.valueOf(psmclist);
    }

    /*查询公共资源交易中心*/
    public String findpsmcInfo() throws Exception {
        JSONArray jsonArray = new JSONArray();
        String findpsmcInfo = "select zx.id,zx.name from ghjl c,psmc zx where c.is_deleted='0' and c.jyzx=zx.id and c.yh ='" + userInfo.getUserId() + "'";
        List<CCObject> psmc = cs.cqlQuery("ghjl", findpsmcInfo);
        if (psmc.size() > 0) {
            for (CCObject cc : psmc) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("label", cc.get("name"));

                jsonObject.put("value", cc.get("id"));
                jsonArray.add(jsonObject);
            }
        }
        JSONObject dataInfo = new JSONObject();
        dataInfo.put("data", jsonArray);
        return String.valueOf(dataInfo);
    }

    /*系统信息*/
    public String systemInfo() throws Exception {
        /*客户开函状态*/
        String accountType = "未开函";
        /*客户跟进状态*/
        String accountFollowUp = "待跟进";


        String userId = "";
        try {
            userId = userInfo.getUserId();
        } catch (Exception e) {
            return String.valueOf(userInfo);
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("khgjzt", accountFollowUp);
        jsonObject.put("khkhzt", accountType);
        JSONObject user = new JSONObject();
        user.put("table", userId);
        user.put("value", userInfo.getUserName());
        jsonObject.put("cjr", user);
        jsonObject.put("syr", user);
        JSONObject dataInfo = new JSONObject();
        dataInfo.put("data", jsonObject);
        return String.valueOf(dataInfo);
    }

    /*电子保函公招信息的所属圈层的下拉列表*/
    public String pickEleOpenCircleInfo() throws Exception {
        List<Object> psmclist = new ArrayList<Object>();
        List<Map> AccountMap = cs.getPicklistValue("ele_open_info", "ssqc", "");
        if (AccountMap.size() > 0) {
            for (Map m : AccountMap) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", m.get("key"));
                jsonObject.put("label", m.get("key"));
                psmclist.add(jsonObject);
            }
        }
        return String.valueOf(psmclist);
    }

    /*电子保函公招信息的主要投标区域的下拉列表*/
    public String pickEleOpenMainAreaInfo() throws Exception {
        List<Object> psmclist = new ArrayList<Object>();
        List<Map> AccountMap = cs.getPicklistValue("ele_open_info", "main_area", "");
        if (AccountMap.size() > 0) {
            for (Map m : AccountMap) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", m.get("key"));
                jsonObject.put("label", m.get("key"));
                psmclist.add(jsonObject);
            }
        }
        return String.valueOf(psmclist);
    }

    /*	客户来源的下拉列表*/
    public String accountSource() throws Exception {
        List<Object> psmclist = new ArrayList<Object>();
        List<Map> AccountMap = cs.getPicklistValue("Account", "source", "");
        if (AccountMap.size() > 0) {
            for (Map m : AccountMap) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", m.get("key"));
                jsonObject.put("label", m.get("key"));
                psmclist.add(jsonObject);
            }
        }
        return String.valueOf(psmclist);
    }

    /*交易中心投标频率的频次的下拉列表*/
    public String peleNumInfo() throws Exception {
        List<Object> psmclist = new ArrayList<Object>();
        List<Map> AccountMap = cs.getPicklistValue("ele_num", "frequece", "");
        if (AccountMap.size() > 0) {
            for (Map m : AccountMap) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", m.get("key"));
                jsonObject.put("label", m.get("key"));
                psmclist.add(jsonObject);
            }
        }
        return String.valueOf(psmclist);
    }


    /*
     * code 社会统一信用代码
     * 通过统一社会信用代码查询客户是否存在crm
     * */
    public boolean isFindAccount(String code) throws Exception {
        String findAccountCode = "select * from account where invoiceTaxNo ='" + code + "' ";
        List<CCObject> account = cs.cqlQuery("account", findAccountCode);
        if (account.size() <= 0) {
            return false;
        } else {
            return true;
        }
    }

    /*
     * code 社会统一信用代码
     * 通过统一社会信用代码查询客户的基本信息
     * */
    public JSONObject findAccountInfo(String code) throws Exception {
        String findAccountCode = "select * from account where invoiceTaxNo ='" + code + "' ";
        List<CCObject> account = cs.cqlQuery("account", findAccountCode);
        JSONObject jsonObject = new JSONObject();
        if (account.size() > 0) {
            jsonObject.put("data", account.get(0));
        } else {
            jsonObject.put("data", "");
        }

        return jsonObject;
    }

    /*
     * code 社会统一信用代码
     * userId  当前登录人的id
     * 通过统一社会信用代码查询客户小组的情况
     * */
    public Boolean findManageGroup(String code, String userId) throws Exception {
        String findManageInfo = "select * from  manage_group where name = '" + code + "' and ghzt = '" + expired + "' and fk_ccuser = '" + userId + "'";
        List<CCObject> manage_group = cs.cqlQuery("manage_group", findManageInfo);
        if (manage_group.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    /*插入客户*/
    public String saveAccountInfo(JSONObject data) throws Exception {
        String name = data.get("khmc") == null ? "" : data.get("khmc") + "";
        String invoiceTaxNo = data.get("tyshxydm") == null ? "" : data.get("tyshxydm") + "";
        String registeredAddress = data.get("zcdz") == null ? "" : data.get("zcdz") + "";
        String zcsf = data.get("zcsf") == null ? "" : data.get("zcsf") + "";
        String zcsq = data.get("zcsq") == null ? "" : data.get("zcsq") + "";
        String zcqx = data.get("zcqx") == null ? "" : data.get("zcqx") + "";
        String full_name = data.get("fddbr") == null ? "" : data.get("fddbr") + "";
        String establishDate = data.get("clrq") == null ? "" : data.get("clrq") + "";
        String follow_status = data.get("khgjzt") == null ? "" : data.get("khgjzt") + "";
        String deal_status = data.get("khkhzt") == null ? "" : data.get("khkhzt") + "";
        String ownerid = data.get("syr") == null ? "" : data.get("syr") + "";
        String createbyid = data.get("cjr") == null ? "" : data.get("cjr") + "";
        String tjkh = data.get("tjkh") == null ? "" : data.get("tjkh") + "";
        String tjyg = data.get("tjyh") == null ? "" : data.get("tjyh") + "";
        String khly = data.get("khly") == null ? "" : data.get("khly") + "";
        String ggzyjyzx = data.get("ggzyjyzx") == null ? "" : data.get("ggzyjyzx") + "";
        String findAccount = "select id,recordtype,follow_status from Account where invoiceTaxNo ='" + invoiceTaxNo + "' and is_deleted='0' ";
        JSONObject dataInfoes = new JSONObject();
        List<CCObject> account = cs.cqlQuery("Account", findAccount);
        if (account.size() > 0) {
            String ACCOUNTTYPE = "待分配";
            String recordType = account.get(0).get("recordtype") == null ? "" : account.get(0).get("recordtype") + "";
            String accountId = account.get(0).get("id") == null ? "" : account.get(0).get("id") + "";
            follow_status = account.get(0).get("follow_status") == null ? "" : account.get(0).get("follow_status") + "";
            if (!recordType.equals(accountType)) {
                String update = "update account set recordtype='" + accountType + "' where id ='" + accountId + "' ";
                cs.cqlQuery("account", update);
            }
//            查询    客户是否为重新拾回
            String findSql = "select id from manage_group where fk_psmc ='" + ggzyjyzx + "' and fk_ccuser='" + ownerid + "' and fk_account='" + accountId + "' and is_deleted='0' and ghzt='已失效' ";
            List<CCObject> manageGroup = cs.cqlQuery("manage_group", findSql);
            if (manageGroup.size() > 0) {
                dataInfoes.put("code", "303");
                dataInfoes.put("msg", "当前客户需求拾回，是否拾回");
                return String.valueOf(dataInfoes);
            }
            String fin = "select id from manage_group where fk_psmc ='" + ggzyjyzx + "' and fk_ccuser='" + ownerid + "' and fk_account='" + accountId + "' and is_deleted='0' and ghzt!='已失效' ";
            List<CCObject> ccObjects = cs.cqlQuery("manage_group",fin);
            if (ccObjects.size()>0){
                dataInfoes.put("code", "305");
                dataInfoes.put("msg", "当前客户，您已经有了管户权");
                dataInfoes.put("id", accountId);
                return String.valueOf(dataInfoes);
            }else {
                String find = "select name from psmc where id ='" + ggzyjyzx + "' ";
                List<CCObject> psmc = cs.cqlQuery("psmc", find);
                if (follow_status.equals(ACCOUNTTYPE)) {
                    dataInfoes.put("code", "304");
                    dataInfoes.put("msg", "客户已经存在于" + psmc.get(0).get("name") + "，是否共享给自己");
                    dataInfoes.put("id", accountId);
                    return String.valueOf(dataInfoes);
                } else {
                    dataInfoes.put("code", "302");
                    dataInfoes.put("msg", "客户已经存在于" + psmc.get(0).get("name") + "，是否领取您对客户的管户权");
                    dataInfoes.put("id", accountId);
                    return String.valueOf(dataInfoes);
                }
            }
        } else {
            String invokeId = UUID.randomUUID().toString().replaceAll("-", "");
            JSONObject requestDataInfo = new JSONObject();
            requestDataInfo.put("invokeId", invokeId);
            JSONObject dataInfo = new JSONObject();
            dataInfo.put("creditCode", invoiceTaxNo);
            requestDataInfo.put("data", dataInfo);

            /*公招信息*/
            CompanyInfoCountService companyInfoCountService = new CompanyInfoCountService(userInfo);
            String s = companyInfoCountService.sendPost(String.valueOf(requestDataInfo));
            JSONObject jsonObject = JSONObject.fromObject(s);


            try {
                JSONObject jsonObjectInfo = jsonObject.getJSONObject("data");
                CCObject eleOpenInfo = new CCObject("ele_open_info ");
                eleOpenInfo.put("first_con_num", jsonObjectInfo.get("registeredConstructorsFirst"));
                eleOpenInfo.put("second_con_num", jsonObjectInfo.get("registeredConstructorsSecond"));
                eleOpenInfo.put("gczzsl", jsonObjectInfo.get("engineeringQualifications"));
                eleOpenInfo.put("main_area", jsonObjectInfo.get("mainBiddingArea"));
                eleOpenInfo.put("main_type", jsonObjectInfo.get("projectCategoryMoreThenFifty"));
                cs.insert(eleOpenInfo);
            } catch (Exception E) {

            }


            /*公商信息*/
            CompanyBaseInfoService information = new CompanyBaseInfoService(userInfo);
            JSONObject requsetInfo1 = new JSONObject();
            JSONObject requsetInfo = new JSONObject();

            requsetInfo1.put("invokeId", invokeId);
            requsetInfo.put("creditCode", invoiceTaxNo);
            requsetInfo1.put("data", requsetInfo);
            String informationInfoList = information.sendPost(String.valueOf(requsetInfo1));
            JSONObject informationInfo = JSONObject.fromObject(informationInfoList).getJSONObject("data");


            /*客户及工商信息*/
            CCObject accountInfo = new CCObject("Account");
            accountInfo.put("name", name);
            accountInfo.put("invoiceTaxNo", invoiceTaxNo);
            String address = informationInfo.getString("regAddress") == null ? "" : informationInfo.getString("regAddress") + "";
            if (!registeredAddress.equals("")) {
                accountInfo.put("registeredAddress", registeredAddress);
            } else {
                accountInfo.put("registeredAddress", address);
            }

            accountInfo.put("full_name", full_name);
            accountInfo.put("establishDate", establishDate);

//            accountInfo.put("province", informationInfo.getString("province"));
//            accountInfo.put("fk_city_name", informationInfo.getString("cityCodeHh"));
//            accountInfo.put("fk_country_name", informationInfo.getString("countyCodeHh"));
            accountInfo.put("province", zcsf);
            accountInfo.put("fk_city_name", zcsq);
            accountInfo.put("fk_country_name", zcqx);
            accountInfo.put("recordtype", accountType);

            accountInfo.put("qyxz", informationInfo.getString("companyType"));
            accountInfo.put("registered_capital", informationInfo.getString("registeredCapital"));
            accountInfo.put("follow_status", follow_status);
            accountInfo.put("deal_status", deal_status);
            accountInfo.put("ownerid", ownerid);
            accountInfo.put("fk_kh", tjkh);
            accountInfo.put("fk_yg", tjyg);
            accountInfo.put("qzkhly", khly);
            accountInfo.put("createbyid", createbyid);
            ServiceResult insert = cs.insert(accountInfo);
            dataInfoes.put("code", "200");
            dataInfoes.put("id", insert.get("id"));
            return String.valueOf(dataInfoes);
        }
    }

    /*插入电子保函公招信息*/
    public void saveEleOpenInfo(JSONObject data) throws Exception {
        String first_con_num = data.get("yjzcjzss") == null ? "" : data.get("yjzcjzss") + "";
        String second_con_num = data.get("ejzcjzss") == null ? "" : data.get("ejzcjzss") + "";
        String gczzsl = data.get("gczzsl") == null ? "" : data.get("gczzsl") + "";
        String main_type = data.get("zytbgclb") == null ? "" : data.get("zytbgclb") + "";
        String main_area = data.get("zytbqy") == null ? "" : data.get("zytbqy") + "";
        String ssqc = data.get("ssqc") == null ? "" : data.get("ssqc") + "";
        String fk_account = data.get("fk_account") == null ? "" : data.get("fk_account") + "";
        CCObject eleOpenInfo = new CCObject("ele_open_info");
        eleOpenInfo.put("first_con_num", first_con_num);
        eleOpenInfo.put("second_con_num", second_con_num);
        eleOpenInfo.put("gczzsl", gczzsl);
        eleOpenInfo.put("main_type", main_type);
        eleOpenInfo.put("main_area", main_area);
        eleOpenInfo.put("ssqc", ssqc);
        eleOpenInfo.put("fk_account", fk_account);
        cs.insert(eleOpenInfo);

    }

    /*插入电子保函频率*/
    public void savaEleNum(JSONObject data) throws Exception {
        String fk_psmc = data.get("ggzyjyzx") == null ? "" : data.get("ggzyjyzx") + "";
        String frequece = data.get("tbpc") == null ? "" : data.get("tbpc") + "";
        String fk_account = data.get("fk_account") == null ? "" : data.get("fk_account") + "";

        CCObject ele_num = new CCObject("ele_num");
        ele_num.put("fk_psmc", fk_psmc);
        ele_num.put("frequece", frequece);
        ele_num.put("fk_account", fk_account);
        cs.insert(ele_num);
    }

    /*
     *共享客户给项目经理
     * accountId 客户Id
     * userId 项目经理id
     */
    public void sharedClient(JSONObject data) throws Exception {
        JSONObject dataInfo = JSONObject.fromObject(data);
        CCObject manage_group = new CCObject("manage_group");
        manage_group.put("fk_account", dataInfo.getString("accountId"));
        manage_group.put("fk_ccuser", dataInfo.getString("userId"));
        manage_group.put("is_shared", dataInfo.getString("is_shared"));
        manage_group.put("province1", dataInfo.getString("province"));
        manage_group.put("fk_city_name1", dataInfo.getString("gfkCityNamehqy"));
        manage_group.put("fk_country_name1", dataInfo.getString("fkCountryName"));
        manage_group.put("name", dataInfo.getString("code"));
        manage_group.put("lxdz", dataInfo.getString("lxdz"));
        manage_group.put("fk_psmc", dataInfo.getString("fk_psmc"));
        manage_group.put("ghzt", lnForce);
        manage_group.put("dlwzco", dataInfo.getString("dlwzco"));
        manage_group.put("dlwzla", dataInfo.getString("dlwzla"));
        cs.insert(manage_group);
    }


    /*城市的数据 前端调用, 城市加区*/
    public String findMapCityInfo() throws Exception {
        String findMapCityInfoSql = "select name,id from city group by name ";
        List<CCObject> cityInfoList = cs.cqlQuery("city", findMapCityInfoSql);
        JSONObject jsonObjectInfo = new JSONObject();
        if (cityInfoList.size() > 0) {
            for (int i = 0; i < cityInfoList.size(); i++) {
                String pid = cityInfoList.get(i).get("id") == null ? "" : cityInfoList.get(i).get("id") + "";
                String pname = cityInfoList.get(i).get("name") == null ? "" : cityInfoList.get(i).get("name") + "";
                String findMapCountryInfo = "select id,name,city from country where city='" + pid + "' and is_deleted ='0' ";
                JSONArray countryList = new JSONArray();
                List<CCObject> countryInfoList = cs.cqlQuery("country", findMapCountryInfo);
                if (countryInfoList.size() > 0) {
                    for (CCObject Info : countryInfoList) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("value", Info.get("id"));
                        jsonObject.put("label", Info.get("name"));
                        jsonObject.put("pid", Info.get("city"));
                        countryList.add(jsonObject);
                    }
                }
                jsonObjectInfo.put(pname, countryList);
            }
        }
        return String.valueOf(jsonObjectInfo);
    }

    /*
     * 通过城市id
     * cityId 城市id
     * */
    public String findMapCityInfo(String cityId) throws Exception {
        String findMapCountryInfo = "select id,name,city from country where city='" + cityId + "' and is_deleted ='0' ";
        List<CCObject> city = cs.cqlQuery("city", findMapCountryInfo);
        JSONArray dataInfo = new JSONArray();
        if (city.size() > 0) {
            for (CCObject cc : city) {
                JSONObject info = new JSONObject();
                info.put("value", cc.get("id"));
                info.put("label", cc.get("name"));
                dataInfo.add(info);
            }
        }
        JSONObject returnDataInfo = new JSONObject();
        returnDataInfo.put("data", dataInfo);
        return String.valueOf(returnDataInfo);
    }

    /*城市的数据 前端调用, 城市加省*/
    public String findProvinceCityInfo() throws Exception {
        String findProvinceCitySql = " select province from city group by province ";
        List<CCObject> cityList = cs.cqlQuery("city", findProvinceCitySql);
        JSONObject jsonObjectInfo = new JSONObject();
        if (cityList.size() > 0) {
            for (int i = 0; i < cityList.size(); i++) {
                String province = cityList.get(i).get("province") == null ? "" : cityList.get(i).get("province") + "";
                String findCitySql = " select id,name,province  from city where province ='" + province + "' and is_deleted='0' ";
                JSONArray countryList = new JSONArray();
                List<CCObject> city = cs.cqlQuery("city", findCitySql);
                if (city.size() > 0) {
                    for (CCObject Info : city) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("value", Info.get("id"));
                        jsonObject.put("label", Info.get("name"));
                        jsonObject.put("pid", Info.get("province"));
                        countryList.add(jsonObject);
                    }
                }
                jsonObjectInfo.put(province, countryList);
            }
        }
        return String.valueOf(jsonObjectInfo);
    }

    /*查询推荐客户*/
    public String findAccount() throws Exception {
        String findAccountSql = "select id,name from account where is_deleted ='0' limit 20";
        List<CCObject> account = cs.cqlQuery("account", findAccountSql);
        JSONArray dataInfoList = new JSONArray();
        if (account.size() > 0) {
            for (CCObject info : account) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", info.get("name"));

                jsonObject.put("label", info.get("id"));
                dataInfoList.add(jsonObject);
            }
        }
        JSONObject dataInfo = new JSONObject();
        dataInfo.put("data", dataInfoList);
        return String.valueOf(dataInfo);
    }

    /*查询推荐客户*/
    public String findAccount(String accountName) throws Exception {
        String findAccountSql = "select id,name from account where is_deleted ='0' and name like '%" + accountName + "%'  limit 50";
        List<CCObject> account = cs.cqlQuery("account", findAccountSql);
        JSONArray dataInfoList = new JSONArray();
        if (account.size() > 0) {
            for (CCObject info : account) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", info.get("name"));
                jsonObject.put("label", info.get("id"));
                dataInfoList.add(jsonObject);
            }
        }
        JSONObject dataInfo = new JSONObject();
        dataInfo.put("data", dataInfoList);
        return String.valueOf(dataInfo);
    }

    /*查询用户*/
    public String findUser() throws Exception {
        String findCCuserSql = "select id,name from ccuser where is_deleted ='0' limit 20";
        List<CCObject> usersInfo = cs.cqlQuery("ccuser", findCCuserSql);
        JSONArray dataInfoList = new JSONArray();
        if (usersInfo.size() > 0) {
            for (CCObject info : usersInfo) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", info.get("name"));
                jsonObject.put("label", info.get("id"));
                dataInfoList.add(jsonObject);
            }
        }
        JSONObject dataInfo = new JSONObject();
        dataInfo.put("data", dataInfoList);
        return String.valueOf(dataInfo);
    }

    /*查询用户*/
    public String findUser(String name) throws Exception {
        String findCCuserSql = "select id,name from ccuser where is_deleted ='0' and name like '%" + name + "%' ";
        List<CCObject> usersInfo = cs.cqlQuery("ccuser", findCCuserSql);
        JSONArray dataInfoList = new JSONArray();
        if (usersInfo.size() > 0) {
            for (CCObject info : usersInfo) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", info.get("name"));
                jsonObject.put("label", info.get("id"));
                dataInfoList.add(jsonObject);
            }
        }
        JSONObject dataInfo = new JSONObject();
        dataInfo.put("data", dataInfoList);
        return String.valueOf(dataInfo);
    }

    /*调用高德地图通过经纬度查询*/
    public String regeo(String location) throws Exception {
        URLConnection con = null;
        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;
        String KEY = "c63b6e45771c81576fc8f52a11cec22a";
        String regeo = "https://restapi.amap.com/v3/geocode/regeo?key=" + KEY;
        regeo += "&location=" + location;
        try {
            URL url = new URL(regeo);
            con = url.openConnection();
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应流
            InputStream inputStream = con.getInputStream();
            //将响应流转换成字符串
            resultBuffer = new StringBuffer();
            String line;
            buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = buffer.readLine()) != null) {
                resultBuffer.append(line);
            }
            return String.valueOf(resultBuffer);

        } catch (Exception e) {
            return String.valueOf(e);
        }
    }

    /*调用高德地图通过地理位置查询经纬度*/
    public String gen(String address) throws Exception {
        URLConnection con = null;
        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;
        String KEY = "c63b6e45771c81576fc8f52a11cec22a";
        String regeo = "https://restapi.amap.com/v3/geocode/geo?key=" + KEY;
        regeo += "&address=" + address;
        try {
            URL url = new URL(regeo);
            con = url.openConnection();
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应流
            InputStream inputStream = con.getInputStream();
            //将响应流转换成字符串
            resultBuffer = new StringBuffer();
            String line;
            buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = buffer.readLine()) != null) {
                resultBuffer.append(line);
            }
            return String.valueOf(resultBuffer);

        } catch (Exception e) {
            return String.valueOf(e);
        }
    }

    /*调用高德地图通过地理位置查询经纬度*/
    public String poi(String keywords) throws Exception {
        URLConnection con = null;
        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;
        String KEY = "c63b6e45771c81576fc8f52a11cec22a";
        String regeo = "https://restapi.amap.com/v5/place/text?parameters&key=" + KEY;
        regeo += "&keywords=" + keywords;
        try {
            URL url = new URL(regeo);
            con = url.openConnection();
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应流
            InputStream inputStream = con.getInputStream();
            //将响应流转换成字符串
            resultBuffer = new StringBuffer();
            String line;
            buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = buffer.readLine()) != null) {
                resultBuffer.append(line);
            }
            return String.valueOf(resultBuffer);

        } catch (Exception e) {
            return String.valueOf(e);
        }
    }

    /*
     * 线下保函管户查询
     * */
    public String postQuerystatus(String data) throws Exception {
        JSONObject returnInfo = new JSONObject();
        HttpURLConnection con = null;
        URL urlnet = null;
        String sc = "";
        String st = "";
        String findHttpRequestSql = "select client_id,client_secret,scope ,grant_type from " +
                "interface_configurat where isstart ='1' " +
                "and port ='" + port + "' and url='" + url + "' and is_deleted='0' ";
        List<CCObject> interface_configurat = cs.cqlQuery("interface_configurat", findHttpRequestSql);
        if (interface_configurat.size() > 0) {
            String client_id = interface_configurat.get(0).get("client_id") == null ? "" : interface_configurat.get(0).get("client_id") + "";
            String client_secret = interface_configurat.get(0).get("client_secret") == null ? "" : interface_configurat.get(0).get("client_secret") + "";
            String scope = interface_configurat.get(0).get("scope") == null ? "" : interface_configurat.get(0).get("scope") + "";
            String grant_type = interface_configurat.get(0).get("grant_type") == null ? "" : interface_configurat.get(0).get("grant_type") + "";
            String token = getLoginToken(client_id, client_secret, scope, grant_type);

            if (!token.equals("")) {
                String urlPost = port + url;
                try {
                    urlnet = new URL(urlPost);
                    con = (HttpURLConnection) urlnet.openConnection();
                    con.setRequestProperty("access_token", token);
                    con.setRequestMethod("POST");
                    con.setDoOutput(true);
                    con.setDoInput(true);
                    con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                    con.setConnectTimeout(50000);
                    con.setReadTimeout(30000);
                    con.connect();
                    OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
                    JSONObject jsonObject = JSONObject.fromObject(data);

                    JSONObject object = JSONObject.fromObject(jsonObject.get("data"));
                    String innerPlatformCode = object.get("innerPlatformCode") == null ? "" : object.get("innerPlatformCode") + "";
                    String findSql = "select uncode from psmc where id ='" + innerPlatformCode + "'";
                    List<CCObject> psmc = cs.cqlQuery("psmc", findSql);
                    if (psmc.size() > 0) {
                        JSONObject dataInfo = JSONObject.fromObject(jsonObject.get("data"));
                        dataInfo.put("innerPlatformCode", psmc.get(0).get("uncode"));
                        jsonObject.put("data", dataInfo);
                        data = String.valueOf(jsonObject);

                    }
                    out.write(data);
                    out.close();
                    //发送文件返回类型
                    if (con.getResponseCode() == 200) {
                        InputStream is = con.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
                        while ((sc = br.readLine()) != null) {
                            st = st + sc;
                        }
                        is.close();
                    }

                    con.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                    st = e.getMessage();
                }
            }
        }
        CCObject interface_record = new CCObject("interface_record");
        interface_record.put("url", url);
        interface_record.put("record_ID", JSONObject.fromObject(data).getString("invokeId"));
        interface_record.put("datas", data);
        interface_record.put("requestDataLong", st);
        cs.insert(interface_record);

        JSONObject info = JSONObject.fromObject(st);

        JSONObject dataInfos = JSONObject.fromObject(info.get("data"));

        if (info.get("resultCode").equals(RESUITCODE)) {
            if (dataInfos.get("bindStatus").equals("Y")) {
                /*已有线下保函信息了 结束*/
                returnInfo.put("code", "502");
                returnInfo.put("msg", "当前客户已存在线下保函系统");
            } else {
                returnInfo.put("code", "200");
                returnInfo.put("msg", "");
            }
        } else if (info.get("resultCode").equals(ERRORCODE)) {
            /*已有线下保函信息了 结束*/
            returnInfo.put("code", "400");
            returnInfo.put("msg", "操作客户失败，未查询到外部平台与内部平台映射关系");
        } else {
            returnInfo.put("code", "400");
            returnInfo.put("msg", info.get("resultMessage"));
        }
        return String.valueOf(returnInfo);
    }

    public String getLoginToken(String client_id, String client_secret, String scope, String grant_type) throws Exception {
        URLConnection con = null;
        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;

        String regeo = getToken + "?client_id=" + client_id + "&client_secret=" + client_secret + "&scope=" + scope + "&grant_type=" + grant_type + "";
        try {
            URL url = new URL(regeo);
            con = url.openConnection();
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应流
            InputStream inputStream = con.getInputStream();
            //将响应流转换成字符串
            resultBuffer = new StringBuffer();
            String line;
            buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = buffer.readLine()) != null) {
                resultBuffer.append(line);
            }
            JSONObject jsonObject = JSONObject.fromObject(String.valueOf(resultBuffer));
            String code = jsonObject.get("code") == null ? "" : jsonObject.get("code") + "";
            String token = "";
            if (code.equals(LOGINGCODE)) {
                String data = jsonObject.get("data") == null ? "" : jsonObject.get("data") + "";
                JSONObject dataInfo = JSONObject.fromObject(data);
                token = dataInfo.get("access_token") == null ? "" : dataInfo.get("access_token") + "";
            }
            return token;

        } catch (Exception e) {
            return String.valueOf(e);
        }
    }


}
